import React, { Component } from 'react';
import fetchJson from '@/utils/fetch';

import Table from '@/components/Table';
import Page from '@/components/Page';
import Dialog from '@/components/Dialog';
import Form from '@/components/Form';

class Banner extends Component {
  constructor (...args) {
    super(...args);
    this.state = {
      datas: [],
      addDialogShow: false,
      delDialogShow: false,
      modDialogShow: false,
      currentMod: null,
      page: 1
    }
  }
  async componentDidMount () {
    await this.getBanner();
  }
  // 获取banner
  async getBanner () {
    let data = await fetchJson('api/banner');
    console.log(data);
    this.setState({
      datas: data
    });
  }
  // 打开修改
  fnModOpen (ID) {
    console.log('修改', ID);
    let currentMod = this.state.datas.filter(item => item.ID === ID)[0];
    this.setState({
      modDialogShow: true,
      currentMod
    });
  }
  // 关闭修改
  fnModClose () {
    this.setState({
      modDialogShow: false
    });
  }
  // 执行修改
  async doModify () {
    let ID = this.state.currentMod.ID;
    let form = this.refs.form_mod.getFormData();
    await fetchJson(`api/banner/${ID}`, {
      method: 'POST',
      body: form
    });
    alert('修改成功');
    await this.getBanner();
    this.fnModClose();
  }
  // 删除
  fnDelete (ID) {
    console.log('删除', ID);
  }
  // 打开添加Dialog
  fnAddOpen () {
    this.setState({
      addDialogShow: true
    })
  }
  // 关闭添加Dialog
  fnAddClose () {
    this.setState({
      addDialogShow: false
    })
  }
  // 提交添加
  async submit () {
    try {
      console.log('提交');
      let form = this.refs.form1.getFormData();
      await fetchJson('api/banner', {
        method: 'POST',
        body: form
      });
      alert('添加成功');
      this.fnAddClose();
      await this.getBanner();
    } catch (e) {
      console.log('添加失败', e)
      if (e.indexOf('login') !== -1) {
        alert('需要先登录');
        this.props.history.push('/login');
      }
    }
  }
  // 打开删除Dialog
  openDelDialog (id) {
    this.del_id = id;
    this.setState({
      delDialogShow: true
    });
  }
  // 关闭删除Dialog
  closeDelDialog () {
    delete this.del_id;
    this.setState({
      delDialogShow: false
    });
  }
  // 删除操作
  async doDelete () {
    let id = this.del_id;
    delete this.del_id;
    await fetchJson(`api/banner/${id}`, {
      method: 'DELETE'
    });
    // 删除成功
    this.closeDelDialog();
    await this.getBanner();
  }
  // 页码变化
  pageChange (page) {
    console.log(page);
    this.setState({
      page
    });
  }
  render() {
    return (
      <div>
        <h1>Banner</h1>
        <button className="btn btn-primary" onClick={this.fnAddOpen.bind(this)}>添加</button>
        <Table
          fields={
            [
              { text: '标题', name: 'title' },
              { text: '副标题', name: 'sub_title' },
              { text: '图片', name: 'image' }
            ]
          }
          datas={this.state.datas}
          onModify={this.fnModOpen.bind(this)}
          onDelete={this.openDelDialog.bind(this)}
        ></Table>
        {/* 分页组件 */}
        <Page
          count={7}
          cur={this.state.page}
          onChange={this.pageChange.bind(this)}
        ></Page>
        {
          this.state.addDialogShow ? (
            <Dialog
              shadow={true}
              title='添加'
              close_btn={true}
              onClose={this.fnAddClose.bind(this)}
            >
              <Form
                ref="form1"
                fields={[
                  {name: 'title', type: 'text', label: '标题', placeholder: '请输入标题'},
                  {name: 'sub_title', type: 'text', label: '副标题', placeholder: '请输入副标题'},
                  {name: 'image', type: 'file', label: '图片', placeholder: ''}
                ]}
                btns={[
                  {text: '提交', type: 'primary', onClick: this.submit.bind(this)},
                  {text: '取消', type: 'default', onClick: this.fnAddClose.bind(this)}
                ]}
              ></Form>
            </Dialog>
          ) : ''
        }
        {/* 删除dialog */}
        {
          this.state.delDialogShow ? (
            <Dialog
              shadow={true}
              title="提示"
              close_btn={true}
              onClose={this.closeDelDialog.bind(this)}
            >
              <div>是否删除 ID: {this.del_id}</div>
              <br/>
              <div style={{textAlign: 'right'}}>
                <button className="btn btn-danger" onClick={this.doDelete.bind(this)}>删除</button>
                <button className="btn btn-default" onClick={this.closeDelDialog.bind(this)}>取消</button>
              </div>
            </Dialog>
          ) : ''
        }
        {/* 修改dialog */}
        {
          this.state.modDialogShow ? (
            <Dialog
              shadow={true}
              title={'修改 ID:' + this.state.currentMod.ID}
              close_btn={true}
              onClose={this.fnModClose.bind(this)}
            >
              <Form
                ref="form_mod"
                fields={[
                  {name: 'title', type: 'text', label: '标题', value: this.state.currentMod.title},
                  {name: 'sub_title', type: 'text', label: '副标题', value: this.state.currentMod.sub_title},
                  {name: 'image', type: 'file', label: '图片'}
                ]}
                btns={[
                  {text: '修改', type: 'primary', onClick: this.doModify.bind(this)},
                  {text: '取消', type: 'default', onClick: this.fnModClose.bind(this)}
                ]}
              ></Form>
            </Dialog>
          ) : ''
        }
      </div>
    );
  }

}

export default Banner;
